#
# Cookbook Name:: mq
# Recipe:: client
#
# Copyright 2013, IBM Corporation
#
# All rights reserved - Do Not Redistribute
#

include_recipe "gitclientsetup"
deployment = node[:deployment]
cuser = node['chef']['user']
cgroup = node['chef']['group']
version = node[:mq][:version]
arch = node[:mq][:arch]
gskver = node[:mq][:gskver]
tmpdir = node[:mq][:tmpdir]

startinstr :mqclient

# Create mqm user and group
group "#{node[:mq][:group]}" do
  action :create
end

user "#{node[:mq][:user]}" do
  gid "#{node[:mq][:group]}"
  home "/var/mqm"
  action :create
end

# Create working directory
directory "#{tmpdir}" do
  user cuser
  action :create
end

# Create target directory
directory "/opt/mqm" do
  owner "#{node[:mq][:user]}"
  group "#{node[:mq][:group]}"
  action :create
end

# Create run time directory
directory "/var/mqm" do
  owner "#{node[:mq][:user]}"
  group "#{node[:mq][:group]}"
  action :create
end

# Fetch installation file
bash "fetch_mq" do
  user cuser
  cwd "#{tmpdir}"
  creates "/tmp/mq/#{node[:mq][:downloadFile]}"
  code <<-EOH
  scp #{node[:common][:scp_repo]}/downloads/mq/#{node[:mq][:downloadFile]} .
  EOH
end
  
# Unzip installation file
bash "unzip_mq" do
  user cuser
  cwd "#{tmpdir}"
  code <<-EOH
  tar xvzf #{node[:mq][:downloadFile]}
  EOH
end

# Accept Licensing
bash "accept_licensing" do
  user "root"
  code <<-EOH
  cd "#{tmpdir}"
  ./mqlicense.sh -accept
  EOH
end  

# Install GSKIT 32 bit
%w(gsk7bas).each do |package|
  rpmout = `rpm -qi #{package}`
  if $? != 0
    yum_package "#{tmpdir}#{package}-#{gskver}.i386.rpm" do
      action :install
    end
  end
end

# Install GSKIT 64 bit
%w(gsk7bas64).each do |package|
  rpmout = `rpm -qi #{package}`
  if $? != 0
    yum_package "#{tmpdir}#{package}-#{gskver}.x86_64.rpm" do
      action :install
    end
  end
end

# Install MQ RPM files
%w(MQSeriesRuntime MQSeriesClient MQSeriesJava MQSeriesKeyMan).each do |package|
  rpmout = `rpm -qi #{package}`
  if $? != 0
    yum_package "#{tmpdir}#{package}-#{version}.#{arch}.rpm" do
      action :install
    end
  end
end

# Update limits.conf
bash "update limits.conf" do
  user "root"
  code <<-EOH
  cnt=`grep "^mqm" /etc/security/limits.conf | wc -l`
  if [[ cnt -le 0 ]] ; then
    echo " " >> /etc/security/limits.conf
    echo "mqm                 -      nproc  4096" >> /etc/security/limits.conf
    echo "mqm                 -      nofile 10240" >> /etc/security/limits.conf
  fi
  EOH
end
  
# Delete working directory
directory "#{tmpdir}" do
  user cuser
  recursive true
  action :delete
end

#

# Add firewall rule
#bash "addfirewallrule for accessing the database" do
#  user "root"
#  code <<-EOH
#  /sbin/iptables -A INPUT -p tcp --dport 50000 -j ACCEPT  
#  EOH
#  not_if "/sbin/iptables -L | grep dpt:mqc_mqinst1"
#end  

#TODO: Need to save iptables for restart


stopinstr :mqclient
